using System;
using System.Collections.Generic;
using System.Text;
using PluginHandler;
using System.IO;
using System.Reflection;

namespace DatabaseManager.Util
{
    /// <summary>
    /// Loads all available plugins in a directory an caches the instances in a generic list
    /// </summary>
    public class PluginChooser
    {
        private List<IPluginHandler> _plugins;

        /// <summary>
        /// Loads all available plugins in a directory an caches the instances in a generic list.
        /// </summary>
        /// <param name="pluginDirectoryPath">The plugin directory path.</param>
        public PluginChooser(string pluginDirectoryPath)
        {
            string[] pluginFilenames = Directory.GetFiles(pluginDirectoryPath, "*.dll");
            _plugins = new List<IPluginHandler>();

            foreach (string pluginFilename in pluginFilenames)
            {
                try
                {
                    Assembly plugin = Assembly.LoadFrom(pluginFilename);

                    Type[] allTypes = plugin.GetTypes();

                    foreach (Type typeItem in allTypes)
                    {
                        if (typeItem.IsClass)
                        {
                            Type pluginInterface = typeItem.GetInterface(typeof(IPluginHandler).FullName);

                            if (pluginInterface != null)
                            {
                                ConstructorInfo pluginConstructor = typeItem.GetConstructor(Type.EmptyTypes);

                                object pluginInstance = pluginConstructor.Invoke(null);
                                IPluginHandler iface = (IPluginHandler)pluginInstance;
                                _plugins.Add(iface);

                                break;
                            }
                        }
                    }
                }
                catch(ReflectionTypeLoadException)
                { }
            }
        }

        /// <summary>
        /// Gets all loaded plugins in the plugin directory path given in the constructor.
        /// </summary>
        /// <value>The loaded plugins.</value>
        public List<IPluginHandler> LoadedPlugins
        {
            get { return _plugins; }
        }

        /// <summary>
        /// Gets the plugin instance by the name of the plugin dll file (without path).
        /// </summary>
        /// <param name="dllName">Name of the DLL (e.g.: SqlPlugin.dll).</param>
        /// <returns></returns>
        public IPluginHandler GetPluginByDLLName(string dllName)
        {
            foreach (IPluginHandler plugin in _plugins)
            {
                if (plugin.GetType().Module.Name.ToLower() == dllName.ToLower())
                {
                    return plugin;
                }
            }

            return null;
        }
    }
}
